package com.online.shopping.service.impl;

import com.online.shopping.mapper.TbContentCategoryMapper;
import com.online.shopping.mapper.TbContentMapper;
import com.online.shopping.pojo.TbContent;
import com.online.shopping.pojo.TbContentExample;
import com.online.shopping.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ContentServiceImpl implements ContentService {

	@Autowired
	private TbContentMapper contentMapper;
	@Autowired
	private TbContentCategoryMapper categoryMapper;

	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public List<TbContent> findAllTbContent() {
		return contentMapper.selectByExample(null);
	}

	@Override
	public TbContent findTbContentById(Long id) {
		return contentMapper.selectByPrimaryKey(id);
	}

	@Override
	public void add(TbContent content) {
		contentMapper.insert(content);

		// 清空redis缓存
		redisTemplate.boundHashOps("content").delete(content.getCategoryId());
	}

	@Override
	public void update(TbContent content) {
		// 清除之前分类的广告缓存
		TbContent oldContent = contentMapper.selectByPrimaryKey(content.getId());
		redisTemplate.boundHashOps("content").delete(oldContent.getCategoryId());

		contentMapper.updateByPrimaryKey(content);
		if(content.getCategoryId() != oldContent.getCategoryId()){
			redisTemplate.boundHashOps("content").delete(content.getCategoryId());
		}
	}

	@Override
	public void delete(Long[] ids) {
		for(Long id : ids){
			TbContent tbContent = contentMapper.selectByPrimaryKey(id);
			redisTemplate.boundHashOps("content").delete(tbContent.getCategoryId());

			contentMapper.deleteByPrimaryKey(id);
		}
	}

	@Override
	public List findAllContentCategory() {
		return categoryMapper.selectByExample(null);
	}

	/**
	 * 首次访问时，如果redis没有数据，就访问数据库，把数据存到redis
	 * 后续访问时，直接查询redis
	 *
	 * 哈希结构
	 *      key     content
	 *                          field           value
	 *                          categoryid      List<TbContent>
	 */
	@Override
	public List<TbContent> findByCategoryId(Long categoryId){


		// 加入缓存的代码
		List<TbContent> list = (List<TbContent>) redisTemplate.boundHashOps("content").get(categoryId);

		if(list == null){
			System.out.println("查询数据库============");
			TbContentExample example = new TbContentExample();
			TbContentExample.Criteria criteria = example.createCriteria();

			// 有效广告
			criteria.andStatusEqualTo("1");
			// 根据categoryId查询
			criteria.andCategoryIdEqualTo(categoryId);
			// 排序
			example.setOrderByClause("sort_order");

			list = contentMapper.selectByExample(example);
			redisTemplate.boundHashOps("content").put(categoryId ,list);
		} else {
			System.out.println("从缓存中获取============");
		}

		return list;
	}
}
